<?php

/* @project : 云影
 * @auther  : 秋水
 * @desc    : 用户模型
 */

namespace app\login\model;

use think\Model;
use think\Db;

class User extends Model {

	/**
	 * 加入分销树
	 * @author 秋水
	 * @DateTime 2018-12-10T14:02:08+0800
	 */
	public function joinTree($uid)
	{
		// 获取配置信息
		$todoConfig = model('TodoConfig')->getConfig();
		$user = $this->where(['id'=>$uid])->find();
		// 已经加入过的
		if($user['isjoin'] == 1) {
			return ['code'=>0,'msg'=>'已经加入过了'];
		}
		$todoFinanceModel = model('TodoFinance');
		// 开始处理积分增减
		Db::startTrans();
		try{
			// 获取树下最大的用户号码
			$max_number = $this->where(['treeid'=>$user['treeid'],'isjoin'=>1])->order('treenumber desc')->find();
			// 用户号码+1
			$user['treenumber'] = $max_number['treenumber']+1;
			// 初始化提现额度
			$user['cashamount'] = $todoConfig['cashmax']['value'];
			$this->where(['id'=>$uid])->update(['treenumber'=>$user['treenumber'],'isjoin'=>1,'cashamount'=>$user['cashamount'],'lasttime'=>time()+365*24*3600]);

			// 获取各级父节点的号码
			$pids = $this->getParentIds($user['treenumber']-1);
			$user['pids'] = implode(',', $pids);
			$user['level'] = count($pids)+1;
			$this->where(['id'=>$uid])->update(['pids'=>$user['pids'],'level'=>$user['level']]);

			// 添加上级父节点的子节点id
			$puser = $this->where(['treeid'=>$user['treeid'],'treenumber'=>$pids[0]])->find();
			if($puser['id'] == $user['parentid']) {
				if(! $puser['child1']>0) {
					$puser_update['child1'] = $uid;
				} else if(! $puser['child2']>0) {
					$puser_update['child2'] = $uid;
				} else if(! $puser['child3']>0) {
					$puser_update['child3'] = $uid;
				}
				if(isset($puser_update)) {
					$this->where(['id'=>$puser['id']])->update($puser_update);
				}
			}

			// 修改上级父节点的直推数
			if($user['parentid'] == $puser['id']) {
				$this->where(['id'=>$puser['id']])->setInc('directcount');
			}

			// 增加提现额度
			$this->where(['id'=>$user['parentid']])->setInc('cashamount', $todoConfig['invitationcash']['value']);

			// 非直推上级奖励（分红）
			$pidsArr = explode(',', $user['pids']);
			if($todoConfig['undirectswitch']['value'] == 1) {
				foreach ($pidsArr as $key => $o) {
					// 获取父节点用户
					$pUser = model('User')->where(['treenumber'=>$o,'treeid'=>$user['treeid']])->find();
					if($pUser) {
						// 添加积分 = 非直推积分*（1-(3-下级直推人数)*助推分红比例）
						$p = $todoConfig['undirectpoint']['value']*(1 - (3-$pUser['directcount'])*$todoConfig['assistrate']['value']);
						$this->where(['id'=>$pUser['id']])->setInc('money',$p);

						// 记录日志
						$logData = [
							'uid' => $pUser['id'],
							'amount' => $p,
							'type' => 2,
							'changetime' => time()
						];
						$todoFinanceModel->insert($logData);
					}
				}
			}

			// 直推父节点的直推数+1
			$this->where(['id'=>$user['parentid']])->setInc('childrencount');
			if($user['isjoin'] == 0) {
				// 会员价格 = 平台收费+直推费用+非直推x9
				$vipPrice = $todoConfig['platform']['value']
					+$todoConfig['directfee']['value']
					+$todoConfig['undirectfee']['value']*$todoConfig['level']['value'];
			} else if($user['isjoin'] == 2) {
				// 会员价格 = 直推费用
				$vipPrice = $todoConfig['directfee']['value'];
			}

			$todoFinanceModel = model('TodoFinance');
			if($user['money'] < $vipPrice) {
				// 用户余额不足
				Db::rollback();
				return ['code'=>0,'msg'=>'余额不足'];
			}
			// 扣除用户的余额
			$r = $this->where(['id'=>$user['id']])->update(['money'=>($user['money']-$vipPrice)]);
			if($r === false) {
				Db::rollback();
				return ['code'=>0,'msg'=>'扣款失败'];
			}
			// 直推上级奖励
			if($todoConfig['directswitch']['value'] == 1) {
				// 直推奖励开关开启时
				$this->where(['id'=>$user['parentid']])->setInc('money',$todoConfig['directpoint']['value']);
				// 记录日志
				$logData = [
					'uid' => $user['parentid'],
					'amount' => $todoConfig['directpoint']['value'],
					'type' => 1,
					'changetime' => time()
				];
				$todoFinanceModel->insert($logData);
			}

			// 助推奖励
			if($todoConfig['assistswitch']['value'] == 1) {
				foreach ($pidsArr as $key1 => $p) {
					// 获取每个上级用户
					$luser = $this->where(['treenumber'=>$p,'treeid'=>$user['treeid']])->find();
					// 上级用户的子节点对应编号
					$children = [3*$luser['treenumber']-1, 3*$luser['treenumber'], 3*$luser['treenumber']+1];
					foreach ($children as $key => $o) {
						// 子节点的助推者奖励
						$pUser = $this->where(['treenumber'=>$o,'treeid'=>$user['treeid']])->find();
						if($pUser) {
							// 如果子节点的父节点与上级用户相同，就不给奖励
							if($pUser['parentid'] == $luser['id']) {
								continue;
							}
							// 添加积分 = 非直推积分*助推分红比例
							$p = $todoConfig['undirectpoint']['value']*$todoConfig['assistrate']['value'];
							$this->where(['id'=>$pUser['parentid']])->setInc('money',$p);
							// 记录日志
							$logData = [
								'uid' => $pUser['parentid'],
								'amount' => $p,
								'type' => 3,
								'changetime' => time()
							];
							$todoFinanceModel->insert($logData);
						}
					}
				}
			}
			Db::commit();
			return ['code'=>1,'msg'=>''];
		} catch(Explode $e){
			Db::rollback();
			return ['code'=>0,'msg'=>$e->getMessage];
		}

		return ['code'=>1,'msg'=>'加入成功'];
	}

	/**
	 * 递归获取父节点的号码
	 * @author 秋水
	 * @DateTime 2018-12-10T14:37:20+0800
	 */
	public function getParentIds($number) {
		if($number<=3) {
			return [1];
		} else {
			$pid = ceil($number/3);
			$r = $this->getParentIds($pid-1);
			return array_merge([$pid],$r);
		}
	}
}